<template>
  <div>
    <el-container class="attachment-upload" v-if="shouldShowAttachment">
      <el-header class="header-class" height="22">
        <div class="header-text">Attachment</div>
      </el-header>
      <el-main class="container-main">
        <el-form label-position="left" ref="validatorForm">
          <el-form-item label="Add Attachment:" :size="form_size" :label-width="label_width" :show-message="false">
            <el-tooltip class="item" effect="dark" content="Click name to download" placement="right"
                        :disabled="!fileList.length">
              <el-upload
                class="upload"
                :action=uploadUrl
                :headers="headers"
                :on-success="onSuccess"
                :on-remove="onRemove"
                :before-upload="onBeforeUpload"
                :file-list="fileList"
                :class="[isReadOnly ? 'upload-status-disable' : '']"
                :accept=acceptFileType
                :disabled="isReadOnly"
                :on-preview="onPreview"
                multiple>
                <el-button size="small" type="primary" ref="uploadBtn" v-show="!isReadOnly">Upload</el-button>
              </el-upload>
            </el-tooltip>

          </el-form-item>
        </el-form>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import * as httpHelper from '@/common/js/httpHelper'
import constants from '@/common/js/constants'
import { REQUEST_FORM } from '@/store/namespaces'
import { createNamespacedHelpers } from 'vuex'
const {mapGetters} = createNamespacedHelpers(REQUEST_FORM)

export default {
  props: {
    uploadUrl: {
      type: String
    },
    acceptFileType: {
      type: String,
      default: 'jpg,gif,png,bmp,doc,txt,pdf,docx,xls,xlsx,zip,msg,rtf,tif,html,htm,rar'
    },
    downloadUrl: {
      type: String
    },
    fileSizeLimit: {
      type: Number,
      default: 1024
    },
    functionList: {
      type: Object,
      default: function () {
        return {
          'update_attachment': true,
          'delete_attachment': true
        }
      }
    }
  },
  data() {
    return {
      form_size: 'mini',
      label_width: '260px',
      fileList: [],
      attachments: [],
      headers: '',
      fileSizeLimitBuffer: 256
      // isReadOnly: false,
    }
  },
  created() {
    this.headers = httpHelper.addAuthenticationHeader()
  },
  computed: {
    ...mapGetters({
      formStatus: 'formStatus'
    }),
    isReadOnly: function () {
      return !((this.functionList.delete_attachment || this.functionList.update_attachment) || (this.formStatus === constants.CREATE_FORM))
    },
    shouldShowAttachment() {
      return !(this.isReadOnly && this.getAttachments().length === 0)
    }
  },
  methods: {
    onSuccess(response, file) {
      file.url = this.downloadUrl + '?fileId=' + response.id
      file.id = response.id
      this.fileList.push(file)
      this.attachments.push(response)
    },
    onRemove(file, fileList) {
      let fileId = file.id
      let index = this.fileList.indexOf(file)
      if (index >= 0) {
        this.fileList.splice(index, 1)
        for (let i = 0; i < this.attachments.length; i++) {
          if (this.attachments[i].id === fileId) {
            this.attachments.splice(i--, 1) // i-- for index change
          }
        }
      }
    },
    onBeforeUpload(file) {
      // validate file size
      let fileSize = file.size
      if ((fileSize.toFixed(2) / 1024) > this.fileSizeLimit + this.fileSizeLimitBuffer) {
        this.$message({
          message: 'File Size can not be larger than ' + this.fileSizeLimit + 'KB',
          type: 'warning'
        })
        return false // return false will trigger on-remove
      }
      // validate file type
      let fileType = file.name.substring(file.name.lastIndexOf('.') + 1)
      let acceptFileTypes = this.acceptFileType.split(',')
      if (acceptFileTypes.indexOf(fileType) < 0) {
        this.$message({
          message: 'The uploaded file type is not allowed',
          type: 'warning'
        })
        return false
      }
      return true
    },
    onPreview(file) {
      this.download(file)
    },
    getAttachments() {
      return this.attachments
    },
    setAttachments(attachments) {
      this.attachments = attachments
      if (attachments !== null && attachments.length > 0) {
        this.fileList = attachments.map((item) => {
          return {
            name: item.fileName,
            url: this.downloadUrl + '?fileId=' + item.id,
            id: item.id
          }
        })
      }
    },
    async download(file) {
      let fileId = file.id
      let fileName = file.name
      let params = {
        'fileId': fileId
      }
      const result = await httpHelper.download(this.downloadUrl, params)
      let blob = new Blob([result.data])
      let elink = document.createElement('a')
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href)
      document.body.removeChild(elink)
    },
    reset() {
      this.fileList = []
      this.attachments = []
    }
  }
}
</script>

<style scoped lang="scss">
  @import './../../common/css/base.scss';

  .container-main {
    border: 1px solid $base-header-color;
  }

  .header-class {
    @include baseHeader(30px)
  }

  .header-text {
    color: #fff;
    margin-top: 5px;
    font-weight: bold;
  }

  .upload {
    width: 500px;
    border: 1px solid $base-header-color;
    padding: 10px;
  }

  .el-upload-list__item-status-label {

  }

</style>

<style>
  .upload-status-disable .el-upload {
    display: none !important
  }
</style>
